<!--
 * Tencent is pleased to support the open source community by making Tars available.
 *
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * https://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>TARS</title>
    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="../css/bootstrap_table.min.css">
    <link rel="stylesheet" href="../css/bootstrap_datepicker.min.css">
    <link rel="stylesheet" href="../css/style.css">

    <!--[if lt IE 9]>
    <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/chart.min.js"></script>
    <script src="../js/template.js"></script>
    <script src="../js/bootstrap_table.min.js"></script>
    <script src="../js/bootstrap_datepicker.min.js"></script>
    <script src="../js/common.js"></script>
    <style>
        .charts_container{overflow:hidden;width: 1200px;margin: 10px auto;}
        .charts_container .chart_box{float:left;width:600px; height:300px;margin-bottom:10px;}
        .chart_box canvas{margin:0 10px;}
        .tool_bar{border:solid 1px #9ed0ff;margin-bottom: 10px;}
        .tool_bar a{display: inline-block;padding:5px;}
    </style>
</head>
<body>
<form class="form-horizontal mt10" role="form">
    <div class="form-group">
        <div class="col-sm-1"><label class="tr wp100 control-label">显示日期</label></div>
        <div class="col-sm-2">
            <input type="text" class="form-control datepicker" id="the_date">
        </div>
        <div class="col-sm-1"><label class="tr wp100 control-label">对比日期</label></div>
        <div class="col-sm-2">
            <input type="text" class="form-control datepicker" id="pre_date">
        </div>
        <div class="col-sm-1"><label class="tr wp100 control-label">开始时间</label></div>
        <div class="col-sm-2">
            <input type="text" class="form-control" id="start_time" value="0000">
        </div>
        <div class="col-sm-1"><label class="tr wp100 control-label">结束时间</label></div>
        <div class="col-sm-2">
            <input type="text" class="form-control" id="end_time" value="2360">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-1"><label class="tr wp100 control-label"><a href="#;" onclick="groupByMaster(this)" data-type="master_name">主调</a></label></div>
        <div class="col-sm-2"><input type="text" class="form-control" id="master_name"></div>
        <div class="col-sm-1"><label class="tr wp100 control-label"><a href="#;" onclick="groupByMaster(this)" data-type="slave_name">被调</a></label></div>
        <div class="col-sm-2"><input type="text" class="form-control" id="slave_name"></div>
        <div class="col-sm-1"><label class="tr wp100 control-label"><a href="#;" onclick="groupByMaster(this)" data-type="interface_name">接口名</a></label></div>
        <div class="col-sm-2"><input type="text" class="form-control" id="interface_name"></div>
        <div class="col-sm-1"><label class="tr wp100 control-label"><a href="#;" onclick="groupByMaster(this)" data-type="master_ip">主调IP</a></label></div>
        <div class="col-sm-2"><input type="text" class="form-control" id="master_ip"></div>
    </div>
    <div class="form-group">
        <div class="col-sm-1"><label class="tr wp100 control-label"><a href="#;" onclick="groupByMaster(this)" data-type="slave_ip">被调IP</a></label></div>
        <div class="col-sm-2"><input type="text" class="form-control" id="slave_ip"></div>
    </div>
    <div class="tc mb10"><button type="button" class="btn btn-primary" id="btn-submit">监控曲线</button></div>
    <div class="tc mb10 gray">(系统初次搭建时，对比日无数据请将对比日期改成显示日期)</div>
</form>

<div class="charts_container">
    <div class="chart_box"><canvas id="chart1" style="width:600px;height:300px;"></canvas></div>
    <div class="chart_box" ><canvas id="chart2" style="width:600px;height:300px;"></canvas></div>
    <div class="chart_box"><canvas id="chart3" style="width:600px;height:300px;"></canvas></div>
    <div class="chart_box"><canvas id="chart4" style="width:600px;height:300px;"></canvas></div>
</div>
<div class="tool_bar">
</div>
<div id="table_box"></div>

<script type="text/html" id="tpl">
    <table class="table table-bordered" id="curve_data">
        <thead>
        <tr>
            <th class="sort">时间点</th>
            <th class="sort">主调</th>
            <th class="sort">被调</th>
            <th class="sort">接口名</th>
            <th class="sort">主调IP</th>
            <th class="sort">被调IP</th>
            <th class="sort">当日总流量</th>
            <th class="sort">对比日总流量</th>
            <th class="sort">同比波动</th>
            <th class="sort">当日平均耗时</th>
            <th class="sort">对比日平均耗时</th>
            <th class="sort">当日异常率</th>
            <th class="sort">对比日异常率</th>
            <th class="sort">当日超时率</th>
            <th class="sort">对比日超时率</th>
        </tr>
        </thead>
        <tbody>
        {{each data as it}}
        <tr class="data-row">
            <td>{{if it.show_time}}{{it.show_time}}{{else}}{{it.show_date}}{{/if}}</td>
            <td><a class="condition-column" href="#;" data-type="master_name" onclick="showTime('{{it.show_time}}',this)">{{it.master_name}}</a></td>
            <td><a class="condition-column" href="#;" data-type="slave_name" onclick="showTime('{{it.show_time}}',this)">{{it.slave_name}}</a></td>
            <td><a class="condition-column" href="#;" data-type="interface_name" onclick="showTime('{{it.show_time}}',this)">{{it.interface_name}}</a></td>
            <td><a class="condition-column" href="#;" data-type="master_ip" onclick="showTime('{{it.show_time}}',this)">{{it.master_ip}}</a></td>
            <td><a class="condition-column" href="#;" data-type="slave_ip" onclick="showTime('{{it.show_time}}',this)">{{it.slave_ip}}</a></td>
            <td>{{it.the_total_count}}</td>
            <td>{{it.pre_total_count}}</td>
            <td>{{it.total_count_wave}}</td>
            <td>{{it.the_avg_time}}ms</td>
            <td>{{it.pre_avg_time}}ms</td>
            <td>{{it.the_fail_rate}}</td>
            <td>{{it.pre_fail_rate}}</td>
            <td>{{it.the_timeout_rate}}</td>
            <td>{{it.pre_timeout_rate}}</td>
        </tr>
        {{/each}}
        </tbody>
        <tfoot>
        <tr>
            <td colspan="15" class="tpage"></td>
        </tr>
        </tfoot>
    </table>
</script>

<script>
    var myDate = new Date(),
        preDate = new Date(new Date().setDate(myDate.getDate()-1)),
        gData = {};

    var treeId = parent.tarsTree.treeId ? parent.tarsTree.treeId : getQueryStringArgs().treeId,
            params = treeId.split('.'),
            paramMap = {};
    $.each(params,function (index,n) {
        paramMap[n.substring(0,1)] = n.substring(1);
    });
    gData.level = params[params.length-1].substring(0,1);
    gData.application = paramMap[1];
    gData.set_name = paramMap[2];
    gData.set_area = paramMap[3];
    gData.set_group = paramMap[4];
    gData.server_name = paramMap[5];

    if(gData.level==1){
        $('body').html('<div class="alert alert-info mt10">服务监控需要具体到服务，请您先在左侧业务树选择服务。</div>');
    }else{
        var a=[];
        $.each(params,function (index,n) {
            a.push(n.substring(1));
        });
        var slaveName = ([gData.application,gData.server_name].join('.')+'.'+[gData.set_name,gData.set_area,gData.set_group].join('')).replace(/\.$/,'');

        $('#slave_name').val(slaveName);

        $('#the_date').val(myDate.getFullYear()+'/'+format(myDate.getMonth()+1)+'/'+format(myDate.getDate()));
        $('#pre_date').val(preDate.getFullYear()+'/'+format(preDate.getMonth()+1)+'/'+format(preDate.getDate()));

        $('.datepicker').datepicker({
            format: 'yyyy/mm/dd'
        });

        renderToolBar();

        getData({
            thedate        :    $('#the_date').val().replace(/\//g,''),
            predate        :    $('#pre_date').val().replace(/\//g,''),
            startshowtime  :    $('#start_time').val(),
            endshowtime	   : 	$('#end_time').val(),
            slave_name	   :    $.trim($('#slave_name').val())
        });
    }




    $('#btn-submit').click(function(){
        var paramObj = {
            thedate        :    $('#the_date').val().replace(/\//g,''),
            predate        :    $('#pre_date').val().replace(/\//g,''),
            startshowtime  :    $('#start_time').val(),
            endshowtime	   : 	$('#end_time').val(),
            master_name	   : 	$.trim($('#master_name').val()),
            slave_name	   : 	$.trim($('#slave_name').val()),
            interface_name : 	$.trim($('#interface_name').val()),
            master_ip	   : 	$('#master_ip').val()
        };
        getData(paramObj);
    });
    Chart.defaults.scale.ticks.autoSkipPadding=17;
    Chart.defaults.global.tooltips.intersect=false;
    Chart.defaults.global.elements.line.borderWidth=1;
    Chart.defaults.global.elements.line.borderColor='rgba(249,103,104,1)';
    Chart.defaults.global.elements.line.backgroundColor='rgba(0,0,0,0)';
    Chart.defaults.global.elements.point.radius=0;

    Chart.defaults.global.responsive=false;
    var ctx1 = document.getElementById("chart1"),
            ctx2 = document.getElementById("chart2"),
            ctx3 = document.getElementById("chart3"),
            ctx4 = document.getElementById("chart4"),
            chart1,chart2,chart3,chart4;

    chart1 = newChart(ctx1,'总流量');
    chart2 = newChart(ctx2,'平均耗时');
    chart3 = newChart(ctx3,'异常率');
    chart4 = newChart(ctx4,'超时率');

    function newChart(tar,label) {
        return new Chart(tar,{
            type:'line',
            data:{
                labels:[],
                datasets:[
                    {data:[],borderColor:'rgba(249,103,104,1)',label:'当日'+label},
                    {data:[],borderColor:'rgba(69,190,137,1)',label:'对比日'+label}
                ]
            },
            options:{
                title:{text:label,display:true}
            }
        });
    }

    function addData(chart, label, data) {
        chart.data.labels = label;
        $.each(chart.data.datasets,function (index,n) {
            n.data = data[index];
        });
        chart.update();
    }

    function showChart(data){
        var arrLabel = [],
                theTotalCount = [],
                preTotalCount = [],
                theAvgTime = [],
                preAvgTime = [],
                theTimeoutRate = [],
                preTimeoutRate = [],
                theFailRate = [],
                preFailRate = [];
        $.each(data.data,function(index,n){
            arrLabel.push(n.show_time);
            theTotalCount.push(n.the_total_count);
            preTotalCount.push(n.pre_total_count);
            theAvgTime.push(n.the_avg_time);
            preAvgTime.push(n.pre_avg_time);
            theTimeoutRate.push(n.the_timeout_rate);
            preTimeoutRate.push(n.pre_timeout_rate);
            theFailRate.push(n.the_fail_rate);
            preFailRate.push(n.pre_fail_rate);
        });

        addData(chart1,arrLabel,[theTotalCount,preTotalCount]);
        addData(chart2,arrLabel,[theAvgTime,preAvgTime]);
        addData(chart3,arrLabel,[theFailRate,preFailRate]);
        addData(chart4,arrLabel,[theTimeoutRate,preTimeoutRate]);
    }

    // 渲染工具条
    function renderToolBar() {
        var str = '<a href="#;" data-value="all">全部</a>';
        for(var i=0;i<24;i++){
            str += '<a href="#;" data-value="'+i+'">'+format(i)+'</a>';
        }
        $('.tool_bar').html(str);
        $('.tool_bar').on('click','a',function () {
            var obj = {},$self = $(this);
            if($self.data('value')=='all'){
                showTable(gData);
                return;
            }
            obj.data = [];
            $.each(gData.data,function (index, n) {
                if(format(parseInt(n.show_time/100))==$self.data('value')){
                    obj.data.push(n);
                }
            });
            showTable(obj);
        });
    }

    function showTable(data){
        var htmlStr,$box = $('#table_box');
        htmlStr = template('tpl',data);
        $box.html(htmlStr);
        $('#curve_data').table();
    }


    function getData(param,isGroupBy){
        $.each(param,function(key,value){
            if(!value){
                delete param[key];
            }
        });
        var paramstr=$.param(param);
        $.getJSON('/pages/server/api/tarsstat_monitor_data?'+paramstr,function(data){
            if(data.ret_code==200 && data.data.length){
                gData.data = data.data;
                showTable(data);
                if(!isGroupBy){
                    $('.charts_container').show();
                    showChart(data);
                }else{
                    $('.charts_container').hide();
                }
            }else{
                $('.charts_container').hide();
                $('#table_box').html('<div class="ta_c" style="padding:20px;">没有数据</div>');
            }
        });
    }

    function showTime(time,tar){
        $('#start_time').val(time || '0000');
        $('#end_time').val(time || '2360');

        $(tar).parents(".data-row").find(".condition-column").each(function (i, a) {
            if ($(a).text() != '%') {
                $('#' + $(a).attr('data-type')).val($(a).text());
            }
        });

        groupByMaster(tar);
    }

    function groupByMaster(tar){
        var type = $(tar).attr('data-type');
        var paramObj = {
            thedate        :    $('#the_date').val().replace(/\//g,''),
            predate        :    $('#pre_date').val().replace(/\//g,''),
            startshowtime  :    $('#start_time').val(),
            endshowtime    :    $('#end_time').val(),
            master_name    :    $.trim($('#master_name').val()),
            slave_name     :    $.trim($('#slave_name').val()),
            interface_name :    $.trim($('#interface_name').val()),
            master_ip      :    $('#master_ip').val(),
            group_by       :    type
        };
        getData(paramObj,true);
    }

    function format(n){
        return n<10 ? '0'+n : n;
    }
</script>
</body>
</html>
